package com.example.mall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.example.mall.product.service.BrandService;
import com.example.mall.product.service.CategoryBrandRelationService;
import com.example.mall.product.vo.Catelog2Vo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.utils.PageUtils;
import com.example.common.utils.Query;

import com.example.mall.product.dao.CategoryDao;
import com.example.mall.product.entity.CategoryEntity;
import com.example.mall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;
    @Autowired
    StringRedisTemplate redisTemplate;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    /***
     * 查询出所有的一级菜单
     * @return
     */
    @Override
    public List<CategoryEntity> listWithTree() {
        //1查出所有的分类
        List<CategoryEntity> entities = baseMapper.selectList(null);
        //2组装成父子的树形结构
        //所有一级分类
        List<CategoryEntity> level1Menu = entities.stream().filter((categoryEntity) -> {
            return categoryEntity.getParentCid() == 0;
        }).map((menu) -> {
            menu.setChildren(getChildrens(menu, entities));
            return menu;
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());
        return level1Menu;
    }


    @Override
    public void removeMenuByIds(List<Long> asList) {
        //TODO 检查当前菜单,是否被其他地方引用

        baseMapper.deleteBatchIds(asList);
    }

    /**
     * 属性分组  新增页面  所属分类 回显
     * @param catelogId
     * @return
     */
    @Override
    public Long[] findCateLogPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();
        //调用递归函数
        List<Long> parentPath = findParentPath(catelogId, paths);
        //逆序
        Collections.reverse(parentPath);
        return (Long[]) parentPath.toArray(new Long[parentPath.size()]);
    }

    /**
     * 级联更新所有的数据
     * @param category
     * @CacheEvict 失效模式
     * @Caching 同时进行缓存多种操作
     * @CacheEvict(value = "category",allEntries = true) 指定删除某个分区下的所有数据
     */
    @Caching(evict = {
            @CacheEvict(value = "category",key = "getLevel1Categorys"),
            @CacheEvict(value = "category",key = "getCatelogJson")
    })

    @Transactional
    @Override
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(),category.getName());
    }

    /**
     * 查出所有的一级分类
     * @return
     */
    /**
     * @Cacheable({"category"})
     *  代表当前方法的结果需要缓存， 如果缓存中有 方法不在调用
     *  如果缓存中没有 则会调用该方法 最后将方法的结果放入缓存
     *  默认行为：
     *  1)如果缓存中有 方法不用调用
     *  2）key 默认生成
     *  3）缓存的value值 默认
     *  4）默认ttl时间 -1
     *自定义：
     * 1）指定生成的缓存使用key   key属性指定 接收Spel表达式
     * 2）指定缓存的数据存活时间  配置文件中修改ttl
     * 3）将数据保存为json格式
     */
    @Cacheable(value={"category"},key = "#root.method.name")
    @Override
    public List<CategoryEntity> getLevel1Categorys() {
        List<CategoryEntity> categoryEntities = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("cat_level", 1));
        return categoryEntities;
    }


    /**
     * 缓存功能 :商城首页三级分类缓存
     * @return
     */
    //@Override
    public Map<String, List<Catelog2Vo>> getCatelogJson2(){
        //给缓存中放入json字符串 拿出的json字符串 还要逆转为能用的对象类型【序列化与反序列化】
        /**
         * 1.空结果缓存：解决缓存穿透
         * 2.设置过期时间(加随机值)：解决缓存雪崩
         * 3.设置锁：解决缓存击穿
         */

        //1.加入缓存逻辑 缓存中的数据是Json字符串
        String catalogJson = redisTemplate.opsForValue().get("catelogJSON");
        if (StringUtils.isEmpty(catalogJson)){
            //2.缓存中没有数据 则去查询数据库
            Map<String, List<Catelog2Vo>> catelogJsonFromDb = getCatelogJsonFromDbWithLocalLock();

            return catelogJsonFromDb;
        }
        //将json转为指定对象
        Map<String, List<Catelog2Vo>> result = JSON.parseObject(catalogJson, new TypeReference<Map<String, List<Catelog2Vo>>>(){});

        return result;
    }


    /**
     * 自定义三级分类的Json数据 (从数据库查询并封装的分类数据)
     * @return
     */

    public Map<String, List<Catelog2Vo>> getCatelogJsonFromDbWithLocalLock() {
        //只要是同一把锁 就能锁住这个锁的所有线程
        //TODO 本地锁 synchronized JUC(lock)
        //1,synchrroonized(this)  springboot所有组件在容器中是单例的
        synchronized (this){
            //得到锁以后 再去缓冲中确定一次是否有数据 如果没有再继续查询
            return getDataFromDb();

        }


    }

    @Cacheable(value = "category" ,key = "#root.methodName")
    @Override
    public Map<String, List<Catelog2Vo>> getCatelogJson(){

        List<CategoryEntity> level1Categorys = getLevel1Categorys();

        Map<String, List<Catelog2Vo>> parent_cid = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            //查询该一级分类的二级分类
            List<CategoryEntity> categoryEntities = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", v.getCatId()));
            //封装上面的结果
            List<Catelog2Vo> catelog2Vos = null;
            if (categoryEntities != null) {
                catelog2Vos = categoryEntities.stream().map(l2 -> {
                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                    //找当前分类的三级分类封装成Vo
                    List<CategoryEntity> level3 = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", l2.getCatId()));
                    if (level3 != null) {
                        List<Catelog2Vo.Catelog3Vo> collect = level3.stream().map(l3 -> {
                            Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                            return catelog3Vo;
                        }).collect(Collectors.toList());
                        catelog2Vo.setCatalog3List(collect);
                    }

                    return catelog2Vo;
                }).collect(Collectors.toList());
            }

            return catelog2Vos;
        }));

        return parent_cid;
    }


    public Map<String, List<Catelog2Vo>> getCatelogJsonFromDbWithRedisLock() {
            //1.设置分布锁 去redis中占坑  //2.设置过期时间，必须和加锁是同步的 保持原子性
        Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock","111",300,TimeUnit.SECONDS);
        if (lock){
            //加锁成功
            //2.设置过期时间，必须和加锁是同步的 保持原子性
           // redisTemplate.expire("lock",30,TimeUnit.SECONDS);
            Map<String, List<Catelog2Vo>> dataFromDb = getDataFromDb();
            redisTemplate.delete("lock");  //删除锁
            return dataFromDb;
        }else{
            //加锁失败
            //休眠100ms重试
            return getCatelogJsonFromDbWithRedisLock();
        }

    }

    private Map<String, List<Catelog2Vo>> getDataFromDb() {
        //得到锁以后 再去缓冲中确定一次是否有数据 如果没有再继续查询
        String catelogJson = redisTemplate.opsForValue().get("catelogJSON");
        if (!StringUtils.isEmpty(catelogJson)) {
            //缓存不为空  直接返回
            Map<String, List<Catelog2Vo>> result = JSON.parseObject(catelogJson, new TypeReference<Map<String, List<Catelog2Vo>>>() {
            });
            return result;
        }


        List<CategoryEntity> level1Categorys = getLevel1Categorys();

        Map<String, List<Catelog2Vo>> parent_cid = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            //查询该一级分类的二级分类
            List<CategoryEntity> categoryEntities = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", v.getCatId()));
            //封装上面的结果
            List<Catelog2Vo> catelog2Vos = null;
            if (categoryEntities != null) {
                catelog2Vos = categoryEntities.stream().map(l2 -> {
                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                    //找当前分类的三级分类封装成Vo
                    List<CategoryEntity> level3 = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", l2.getCatId()));
                    if (level3 != null) {
                        List<Catelog2Vo.Catelog3Vo> collect = level3.stream().map(l3 -> {
                            Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                            return catelog3Vo;
                        }).collect(Collectors.toList());
                        catelog2Vo.setCatalog3List(collect);
                    }

                    return catelog2Vo;
                }).collect(Collectors.toList());
            }

            return catelog2Vos;
        }));
        //3.将查到的数据放入缓存,将对象转为JSON放入缓存中
        String s = JSON.toJSONString(parent_cid);
        redisTemplate.opsForValue().set("catelogJSON", s, 1, TimeUnit.DAYS);
        return parent_cid;
    }


    /**
     * 使用递归查找当前catelogId 的父id并组装成数组
     * @param catelogId
     * @param paths
     * @return
     */
    private List<Long> findParentPath(Long catelogId,List<Long> paths ){
        //收集当前节点id
        paths.add(catelogId);
        CategoryEntity byId = this.getById(catelogId);
        if(byId.getParentCid()!=0){
            findParentPath(byId.getParentCid(),paths);
        }

        return paths;
    }


    /**
     * 递归查找当前菜单的子菜单
     */
    private List<CategoryEntity> getChildrens(CategoryEntity root, List<CategoryEntity> all) {
        List<CategoryEntity> children = all.stream().filter((categoryEntity) -> {
            return categoryEntity.getParentCid() == root.getCatId(); //当前菜单父id == 指定id
        }).map((categoryEntity) -> {
            //继续找子菜单
            categoryEntity.setChildren(getChildrens(categoryEntity, all));
            return categoryEntity;
        }).sorted((menu1, menu2) -> {
            //菜单排序
            return (menu1.getSort()==null?0:menu1.getSort())-(menu2.getSort()==null?0:menu2.getSort());
        }).collect(Collectors.toList());

        return children;
    }

}


